<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form class="member-info" :model="{users}" ref="userForm">
        <div class="member-info-item" v-for="(user,index) in users" :key="index">
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="{
            required:true,
            message:'乘机人姓名不能为空',
            trigger:'blur'
          }"
          >
            <el-input
              placeholder="姓名"
              class="input-with-select"
              v-model="user.username"
              @focus="clearUserErr(`users[${index}].username`)"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
          {
            required:true,
            message:'乘机人证件号码不能为空',
            trigger:'blur'
          },
          {
            pattern:/^\d{18}$/,
            message:'乘机人证件号码格式不合法',
            trigger:'blur'
          }
          ]"
          >
            <el-input
              placeholder="证件号码"
              class="input-with-select"
              v-model="user.id"
              @focus="clearUserErr(`users[${index}].id`)"
            >
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <el-checkbox-group v-model="insurances">
          <div class="insurance-item" v-for="(item,index) of data.insurances" :key="index">
            <el-checkbox
              :label="item.id"
              border
            >{{item.type}}：￥{{item.price}}/份×{{users.length}} 最高赔付{{item.compensation}}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="80px"
          :model="{
          contactName,contactPhone,captcha
        }"
          :rules="contactRules"
          ref="contactForm"
          class="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName" @focus="clearUserErr(contactName)"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input
              placeholder="请输入内容"
              v-model="contactPhone"
              @focus="clearUserErr(contactPhone)"
            >
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha" @focus="clearUserErr(captcha)"></el-input>
          </el-form-item>
        </el-form>
        <el-button
          v-if="$store.state.user.userInfo.token"
          type="warning"
          class="submit"
          @click="handleSubmit"
        >提交订单</el-button>
        <!-- 未登录状态下显示登录与注册表单 -->
        <el-row v-else type="flex" justify="center" align="middle" class="loginForm">
          <div class="form-wrapper">
            <!-- 表单头部tab -->
            <el-row type="flex" justify="center" class="tabs">
              <span
                :class="{active: currentTab === index}"
                v-for="(item, index) in [`登录`, `注册`]"
                :key="index"
                @click="handleChangeTab(index)"
              >{{item}}</span>
            </el-row>
            <!-- 登录页面 -->
            <loginForm v-if="currentTab==0" />
            <!-- 注册页面 -->
            <RegisterForm v-if="currentTab==1" @logintab="currentTab =0" />
          </div>
        </el-row>
      </div>
      <div style="display:none">{{totalPrice}}</div>
    </div>
  </div>
</template>

<script>
import RegisterForm from "@/components/user/registerForm";
import loginForm from "@/components/user/loginForm";
export default {
  components: {
    loginForm,
    RegisterForm
  },
  props: {
    data: Object
  },
  data() {
    return {
      currentTab: 0,
      users: [
        //   这个数组负责管理乘机人
        {
          username: "",
          id: ""
        }
      ],
      insurances: [],
      contactName: "",
      contactPhone: "",
      captcha: "",
      contactRules: {
        contactName: [
          {
            required: true,
            message: "请输入联系人的姓名",
            trigger: "blur"
          }
        ],
        contactPhone: [
          {
            required: true,
            message: "请输入联系人的手机号",
            trigger: "blur"
          }
        ],
        captcha: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur"
          }
        ]
      }
    };
  },

  watch: {
    users() {
      this.$emit("userLength", this.users.length);
    }
  },
  computed: {
    totalPrice() {
      let price =
        this.users.length *
        (this.data.seat_infos.org_settle_price + this.data.airport_tax_audlet);
      this.data.insurances.forEach(element => {
        if (this.insurances.indexOf(element.id) >= 0) {
          price += element.price * this.users.length;
        }
      });
      this.$emit("setTotalPrice", price);
      return price;
    }
  },
  methods: {
    // 登录与注册的切换
    handleChangeTab(index) {
      this.currentTab = index;
    },
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: ""
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      if (!this.contactPhone || this.contactPhone.length !== 11) {
        this.$confirm("请输入正确的手机号", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        return;
      }
      this.$axios({
        url: "/captchas",
        method: "post",
        data: {
          tel: this.contactPhone
        }
      }).then(res => {
        // console.log(res.data);
        this.$message.success(`已成功发送验证码:${res.data.code}`);
      });
    },

    // 提交订单
    async handleSubmit() {
      let userValid = this.$refs.userForm.validate().catch(err => {});
      let contactValid = this.$refs.contactForm.validate().catch(err => {});
      if (userValid && contactValid) {
        const data = {
          users: this.users,
          insurances: this.insurances,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: true,
          captcha: this.captcha,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id
        };
        this.$axios({
          url: "/airorders",
          method: "post",
          data,
          headers: {
            Authorization:
              "Bearer" + " " + this.$store.state.user.userInfo.token
          }
        }).then(res => {
          console.log(res.data);
          this.$router.push({
            path: "/air/pay",
            query: {
              id: res.data.data.id
            }
          });
        });
      } else {
        this.$confirm("信息不能为空", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        return;
      }
    },
    // 清理输入框错误提示
    clearUserErr(newPropName) {
      this.$refs.userForm.clearValidate(newPropName);
      this.$refs.contactForm.clearValidate(newPropName);
    }
  }
};
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
  .el-form-item__error {
    padding-left: 134px;
  }
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 18px;
  height: 18px;
  font-size: 16px;
  text-align: center;
  line-height: 18px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  .contactForm {
    /deep/ .el-input {
      width: 50%;
    }
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
// 登录与注册表单
.loginForm {
  height: 100%;
  margin: 0 auto;
  position: relative;
  .form-wrapper {
    width: 400px;
    background-color: #fff;
    border: 2px solid #dddddd;
    overflow: hidden;
    .tabs {
      span {
        display: block;
        width: 200px;
        height: 50px;
        line-height: 48px;
        border-top: 2px solid #eee;
        box-sizing: border-box;
        text-align: center;
        background-color: #eeeeee;
        color: #666;
        cursor: pointer;
        &.active {
          color: #ffa500;
          border-top: 2px solid #ffa500;
          background-color: #fff;
          font-weight: bold;
        }
      }
    }
  }
}
</style>